package com.yfp.file.controller;

import com.yfp.common.core.domain.R;
import com.yfp.common.core.utils.file.FileUtils;
import com.yfp.file.domain.FileProperty;
import com.yfp.file.domain.MultipartUploadDto;
import com.yfp.file.service.ISysFileService;
import com.yfp.system.api.domain.SysFile;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件请求处理
 *
 *
 */
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Resource
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
//    @RequiresPermissions("system:file:add")
    public R<SysFile> upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    @PostMapping("uploadByType")
    // 校验参数
    public R<SysFile> uploadByType(MultipartFile file, FileProperty fileProperty) {
        try {
            // 校验文件
            //sysFileService.validateFile(file, fileProperty);
            SysFile sysFile = sysFileService.uploadFileByType(file, fileProperty.getType());
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail("上传文件失败:" + e.getMessage());
        }
    }

    @Operation(summary = "文件上传-获取全局唯一的uploadId")
    @PostMapping("getUploadId")
//    @RequiresPermissions("system:file:add")
    public R<String> getUploadId(String fileName) {
        return R.ok(sysFileService.getUploadId(fileName));
    }


    @Operation(summary = "文件上传-分片上传")
    @PostMapping("partUpload")
//    @RequiresPermissions("system:file:add")
    public R partUpload(MultipartUploadDto param) {
        return sysFileService.partUpload(param);
    }

    @Operation(summary = "文件上传-完成分片上传")
    @PostMapping("completeMultipartUpload")
//    @RequiresPermissions("system:file:add")
    public R completeMultipartUpload(String uploadId) {
        return R.ok(sysFileService.completeMultipartUpload(uploadId));
    }
}